from sqlalchemy import select
from app.api.admin.model.coupon.coupon import CouponCateModel, CouponModel
from app.api.h5.schema.coupon import coupon
from app.api.h5.schema.coupon.coupon import CouponOutSchema
from app.dependencies.database import db


class CouponService:
    async def list(self):
        query = (
            select(
                CouponModel,
                CouponCateModel.name.label("cate_name"),
                )
            .select_from(CouponModel)
            .outerjoin(CouponCateModel, CouponModel.cate_id == CouponCateModel.key)
        )
        records = await db.fetch_all(query)
        coupons = [CouponOutSchema.model_validate(
            item, from_attributes=True) for item in records]
        return [coupon.model_dump(by_alias=True) for coupon in coupons if coupon.status == 1]

    @classmethod
    async def instance(cls):
        return cls()
